<?php

require_once(SRC_PATH."Object/Fetch.php");
require_once(RX_PATH."Date/RXDate.php");
require_once("GenericReader.php");

class FetchReader extends GenericReader{
		
	public function __construct($object = NULL, $connection = NULL){
		parent::__construct($object, $connection);
	}
	
	public function execute(){
		$this->select = new RXSelect($this->connection);
		
		switch($this->operation){
			case "SELECT_ONE_SCHEDULED":
				return $this->executeOneScheduled();
			case "SELECT_ONE_FETCHED": 
				return $this->executeOneFetched();
			case "SELECT_ONE_PROCESSED": 
				return $this->executeOneProcessed();			
		}
	}
	
	public function executeOneScheduled(){
		$this->select->addTable("fetchs");
		$this->select->addWhereAndStatementEquals("status", "0");
		$this->select->addOrderField("last_change", "ASC");
		return $this->select->execute();	
	}
	
	public function executeOneFetched(){
		$this->select->addTable("fetchs");
		$this->select->addWhereAndStatementEquals("status", "2");
		$this->select->addOrderField("last_change", "ASC");
		return $this->select->execute();	
	}
	
	public function executeOneProcessed(){
		$this->select->addTable("fetchs");
		$this->select->addWhereAndStatementEquals("status", "4");
		$this->select->addOrderField("last_change", "ASC");
		return $this->select->execute();	
	}
	
	public function next(){
		$row = $this->select->next();
		if($row){
			$scheduledDate = new RXDate();
			$lastChange = new RXDate();
			$scheduledDate->setUnixTime($row["scheduled_date"]);
			$lastChange->setUnixTime($row["last_change"]);
			return new Fetch(	$row["id"], 
											urldecode($row["location"]), 
											$scheduledDate, 
											$lastChange, 
											$row["status"], 
											$row["ttl"], 
											html_entity_decode(utf8_decode($row["content"])), 
											html_entity_decode(utf8_decode($row["keywords"])), 
											html_entity_decode(utf8_decode($row["paragraphs"])), 
											html_entity_decode(utf8_decode($row["description"])), 
											html_entity_decode(utf8_decode($row["title"])), 
											html_entity_decode(utf8_decode($row["link_title"])), 
											html_entity_decode(utf8_decode($row["link_text"]))
			);
		}else{
			return FALSE;
		}
	}
}